package com.example.controller;


import com.example.common.result.Result;
import com.example.entity.dto.SaleOrder.CopmgListDto;
import com.example.entity.vo.CopmgVo;
import com.example.mapper.CopmgMapper;
import com.example.mapper.CoptdMapper;
import com.example.untils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-03-22
 */
@Api(tags = "客户品号信息")
@RestController
@RequestMapping("/api/copmg")
public class CopmgController {

    @Autowired
    private CopmgMapper mapper;

    @Resource
    private CoptdMapper coptdMapper;


    @ApiOperation("根据客户id,获取客户品号")
    @PostMapping("getCustomProductIdByCustomId")
    public Result<PageInfo<List<CopmgVo>>> getCustomProductIdByCustomId(@RequestBody CopmgListDto dto,
                                                                @RequestParam("customId") String customId,
                                                              @RequestParam(defaultValue = "0") int current,
                                                              @RequestParam(defaultValue = "20")  int size) {
        if(StringUtils.isEmpty(customId.trim())) {
            return Result.error("客户编号不能为空");
        }
        PageHelper.startPage(current,size);
        List<CopmgVo> vos = mapper.getCustomProductIdByCustomId(customId, dto);

        if (!vos.isEmpty()){
            vos.forEach(arr ->{
                Double td010Double = this.coptdMapper.getTd010Double(customId,arr.getMb001());
                if (arr.getNuclearPrice() == null){
                    if (td010Double!=null) {
                        arr.setNuclearPrice(td010Double);
                    }
                }
                if (td010Double!=null){
                    arr.setNuclearPriceLs(td010Double);
                }
            });
        }

        // 取list中相同品号的创建时间最新数据
        Map<String, CopmgVo> map = vos.stream()
                .collect(Collectors.toMap(CopmgVo::getMb001, Function.identity(), (o1, o2) -> o1));
        List<CopmgVo> resultList = new ArrayList<>(map.values());

        if (dto.getMg002()==null || dto.getMg002().equals("")){
            PageInfo<List<CopmgVo>> pageInfo = new PageInfo(resultList);

            return Result.success(pageInfo);
        }else {
            PageInfo<List<CopmgVo>> pageInfo = new PageInfo(vos);

            return Result.success(pageInfo);
        }
    }

}
